var cluster = {
    vector: null,
    provinceSource: null,
    citySource: null,
    countySource: null,
    rqSource: null,
    rqInfoSource: null,
    selectPointerMove: null,
    inputData: null,
    rqInfoVector: null,
    rqInfoName: null,
    rqInfoCenter: null,
    tian_di_tu_annotation: null,
    boundFeat: null,
    mousePosition: null,
    selectStyle: null,
    selectFeature: null,
    clickFeature: null,
    isClick: null,
    init: function () {
        map.on('pointermove', function (evt) {
            cluster.mousePosition = evt.coordinate;
        });
        var style = function (feature, resolution) {
            var type = feature.getGeometry().getType();
            var style = feature.getStyle();
            var text = null;
            if (typeof feature.getProperties().text === 'undefined') {
                text = 'none';
            } else {
                var text = feature.getProperties().text
            }
            feature.setStyle(cluster.getUnselectedPropertyStyle(type, text, style, feature));
        }
        this.vector = new ol.layer.Vector({
            source: this.getProvinceSource(),
            style: style
        });
        map.addLayer(this.vector);
        this.selectPointerMove = new ol.interaction.Select({
            condition: ol.events.condition.pointerMove
        });
        this.selectPointerMove.on('select', function (e) {
            cluster.onPointerMove(e);
        });
        map.addInteraction(this.selectPointerMove);
        map.on('singleclick', function (e) {
            cluster.onPointerClick(e);
        });
        map.getView().on('change:resolution', function (e) {
            cluster.onResChange(e);
        });
        this.reset();
    },
    getProvinceSource: function (id) {
        var source = new ol.source.Vector({
            format: new ol.format.GeoJSON({
                defaultDataProjection: 'EPSG:4326',
                featureProjection: 'EPSG:3857'
            }),
            loader: function (extent, resolution, projection) {
                var url = '../../assets/newMap/data/mapdata/province.json';
                $.getJSON(url, function (data) {
                    var zoom = map.getView().getZoom();
                    var radius = 1e6 / Math.pow(2, zoom - 2.5);
                    var features = source.getFormat().readFeatures(data);
                    $.getJSON('/newMap/initMapData', {
                        currentMap: 'clusterMap',
                        city: '-1',
                        level: '1'
                    }, function (info) {
                        var list = info.result.mapDataList;
                        data.features.forEach(function (item) {
                            var name = item.properties.name;
                            var zoneNumber = item.properties.id + '0000';
                            var text = cluster.getText(list, name, zoneNumber)[0];
                            var count = cluster.getText(list, name, zoneNumber)[1];
                            var center = null;
                            if (item.properties.id == '15') { //内蒙
                                center = [13264576.140496347, 5523033.915773695];
                            }
                            else if (item.properties.id == '62') { //甘肃
                                center = [10710967.899545176, 4896861.780061531];
                            }
                            else if (item.properties.id == '13') { //河北
                                center = [12848147.210398706, 4627803.440497711];
                            }
                            else if (item.properties.id == '61') { //陕西
                                center = [12119855.204897547, 4084794.7915598187];
                            } else {
                                center = ol.proj.transform(item.properties.cp, 'EPSG:4326', 'EPSG:3857');
                            }
                            var feature = new ol.Feature({
                                id: item.properties.id,
                                geometry: new ol.geom.Circle(center, radius),
                                text: text
                            });
                            feature.set('count', count, false);
                            feature.set('type', 'province', false);
                            features.push(feature);
                        });
                        source.addFeatures(features);
                    })
                })
                $("#district option").remove();
                $("#s2id_district span:first").html("行政区");
                var city = $("#city").val()
                $("#district").append("<option value='-1' >行政区</option>")
                if (city == '-1') {
                    return
                }
                $.ajax({
                    url: "/estate/districtList",
                    type: "POST",
                    data: {'city': city},
                    success: function (result) {
                        for (var i = 0; i < result.districtList.length; i++) {
                            $("#district").append("<option value=" + result.districtList[i].zoneNumber + ">" + result.districtList[i].name + "</option>")
                        }
                    }
                });
            }
        });
        source.set('id', 'province');
        this.provinceSource = source;
        return source;
    },
    getCitySource: function (id) {
        var url = '../../assets/newMap/data/mapdata/city/' + id + '.json';
        var source = new ol.source.Vector({
            format: new ol.format.GeoJSON({
                defaultDataProjection: 'EPSG:4326',
                featureProjection: 'EPSG:3857'
            }),
            loader: function (extent, resolution, projection) {
                $.getJSON(url, function (data) {
                    var zoom = map.getView().getZoom();
                    var radius = 1e6 / Math.pow(2, zoom - 2.5);
                    var features = source.getFormat().readFeatures(data);
                    var newid = id + '0000';
                    $.getJSON('/newMap/initMapData', {
                        currentMap: 'clusterMap',
                        province: newid,
                        level: '2'
                    }, function (info) {
                        var list = info.result.mapDataList;
                        features.forEach(function (item) {
                            var name = item.N.name;
                            var zoneNumber = item.N.id + '00';
                            var text = cluster.getText(list, name, zoneNumber)[0];
                            var count = cluster.getText(list, name, zoneNumber)[1];
                            var center = ol.proj.transform(item.N.cp, 'EPSG:4326', 'EPSG:3857');
                            var feature = new ol.Feature({
                                id: item.N.id,
                                name: name,
                                text: text,
                                geometry: new ol.geom.Circle(center, radius)
                            });
                            feature.set('count', count, false);
                            feature.set('type', 'city', false);
                            source.addFeature(feature);
                        })
                    })
                    source.addFeatures(features);
                })
            }
        });
        source.set('id', 'city');
        this.citySource = source;
        return source;
    },
    getCountySource: function (inputData) {
        var url = '../../assets/newMap/data/mapdata/county/' + inputData.city + '.json';
        var source = new ol.source.Vector({
            id: 'county',
            format: new ol.format.GeoJSON({
                defaultDataProjection: 'EPSG:4326',
                featureProjection: 'EPSG:3857'
            }),
            loader: function (extent, resolution, projection) {
                $.getJSON(url, function (data) {
                    var zoom = map.getView().getZoom();
                    var radius = 1e6 / Math.pow(2, zoom - 2.2);
                    var features = source.getFormat().readFeatures(data);
                    $.getJSON('/newMap/initMapData', inputData, function (info) {
                        var list = info.result.mapDataList;
                        features.forEach(function (item) {
                            var name = item.N.name;
                            var zoneNumber = item.N.id;
                            var text = cluster.getText(list, name, zoneNumber)[0];
                            var count = cluster.getText(list, name, zoneNumber)[1];
                            var ext = item.getGeometry().getExtent();
                            var center = ol.extent.getCenter(ext);
                            var feature = new ol.Feature({
                                id: item.N.id,
                                geometry: new ol.geom.Circle(center, radius),
                                text: text
                            });
                            feature.set('count', count, false);
                            feature.set('type', 'county', false);
                            source.addFeature(feature);
                        })
                    });
                    source.addFeatures(features);
                })
                cluster.getArea();
            }
        });
        source.set('id', 'county');
        this.countySource = source;
        return source;
    },
    getRqSource: function (inputData) {
        var url = '/map/mapCommunityData';
        var source = new ol.source.Vector({
            format: new ol.format.GeoJSON({
                defaultDataProjection: 'EPSG:4326',
                featureProjection: 'EPSG:3857'
            }),
            loader: function (extent, resolution, projection) {
                $.ajax({
                    url: url,
                    type: 'POST',
                    async: true,
                    data: inputData,
                    success: function (data) {

                        var list = data.result.mapDataList;
                        var zoom = map.getView().getZoom();
                        var radius = 1e6 / Math.pow(2, zoom - 2.3);
                        var itemf = list[0];
                        var f = [itemf.lng, itemf.lat];

                        map.getView().setCenter(f);
                        list.forEach(function (item) {
                            //var center = ol.proj.transform([item.lng, item.lat], 'EPSG:4326', 'EPSG:3857');
                            var center = [item.lng, item.lat];
                            var text = xdmap.strWrap(item.communityName.replace(/\s/g, ""), 3);
                            var feature = new ol.Feature({
                                id: item.communityId,
                                geometry: new ol.geom.Circle(center, radius),
                                text: text + '\n' + item.count + '笔'
                            });
                            feature.set('name', item.communityName.replace(/\s/g, ""), false);
                            feature.set('count', item.count, false);
                            feature.set('type', 'rq', false);
                            source.addFeature(feature);
                        })

                    }
                })
            }
        })
        source.set('id', 'rq', false);
        this.rqSource = source;
        return source;
    },
    getRqInfoSource: function (inputData, center) {
        var source = new ol.source.Vector({
            format: new ol.format.GeoJSON({
                defaultDataProjection: 'EPSG:4326',
                featureProjection: 'EPSG:3857'
            }),
            loader: function (extent, resolution, projection) {
                var inputData = cluster.getInputData('clusterMap');
                $.ajax({
                    url: '/map/mapCommunityData',
                    type: 'POST',
                    async: true,
                    data: inputData,
                    success: function (data) {
                        if (cluster.rqSource == null) {
                            cluster.rqSource = new ol.source.Vector();
                            var list = data.result.mapDataList;
                            var zoom = map.getView().getZoom();
                            var radius = 1e6 / Math.pow(2, zoom - 3);
                            list.forEach(function (item) {
                                //var center = ol.proj.transform([item.lng, item.lat], 'EPSG:4326', 'EPSG:3857');
                                var center = [item.lng, item.lat];
                                var feature = new ol.Feature({
                                    id: item.communityId,
                                    geometry: new ol.geom.Circle(center, radius),
                                    text: item.communityName.replace(/\s/g, "") + '\n' + item.count + '笔'
                                });
                                feature.set('name', item.communityName.replace(/\s/g, ""), false);
                                feature.set('count', item.count, false);
                                feature.set('type', 'rq', false);
                                cluster.rqSource.addFeature(feature);
                            })
                        }
                        $.ajax({
                            url: '/map/mapBuildingBankData3',
                            type: 'POST',
                            async: true,
                            data: cluster.inputData,
                            success: function (data) {
                                if (data.result.community == null) {
                                    return;
                                }
                                var rqInfocCenter = [data.result.community.arcgisX, data.result.community.arcgisY];
                                map.getView().setCenter(rqInfocCenter);
                                map.getView().setZoom(18);
                                var points = new Array();
                                var resultPoints = new Array()
                                var strPoint = $.trim(data.result.community.bound.slice(7).replace('((', '').replace('))', ''));
                                var point = strPoint.split(',');
                                point.forEach(function (point) {
                                    var arrPoint = $.trim(point).split(' ');
                                    var newArr = ol.proj.transform(arrPoint, 'EPSG:3857', 'EPSG:4326');
                                    points.push(newArr);
                                })
                                resultPoints.push(points);
                                var jsonFeature = {
                                    'type': 'Feature',
                                    'geometry': {
                                        'type': 'Polygon',
                                        'coordinates': resultPoints
                                    }
                                }
                                cluster.boundFeat = source.getFormat().readFeature(jsonFeature);
                                cluster.boundFeat.setStyle(new ol.style.Style({
                                    stroke: new ol.style.Stroke({
                                        color: 'rgba(250,176,117,1)',
                                        width: 2
                                    }),
                                    fill: new ol.style.Fill({
                                        color: 'rgba(255,179,91,0.2)'
                                    })
                                }))
                                cluster.boundFeat.set('info', 'rqBound');
                                source.addFeature(cluster.boundFeat); //小区边界
                                //小区中心
                                cluster.inputData.communityName = data.result.community.communityName;
                                var hourseCount = data.result.community.totalHouseHoldCount;
                                cluster.rqInfoCount = data.result.community.totalBuildingCount;
                                cluster.rqInfoName = data.result.community.communityName;
                                cluster.rqInfoId = cluster.inputData.communityId;
                                var div = cluster.createRightDiv(cluster.inputData.communityName, hourseCount);
                                var centerOverly = new ol.Overlay({
                                    element: div,
                                    position: rqInfocCenter,
                                    offset: [-10, -30],
                                    autoPan: true,
                                    autoPanAnimation: {
                                        duration: 250
                                    }
                                })
                                map.addOverlay(centerOverly);
                                //小区楼栋
                                var divList = cluster.createDiv(data.result.mapDataList);
                                divList.forEach(function (item) {
                                    var div = item[0];
                                    //var point = ol.proj.transform(item[1], 'EPSG:4326', 'EPSG:3857');
                                    var point = item[1];
                                    var overly = new ol.Overlay({
                                        element: div,
                                        position: point,
                                        offset: [-10, -30],
                                        autoPan: true,
                                        autoPanAnimation: {
                                            duration: 250
                                        }
                                    })
                                    map.addOverlay(overly);

                                })
                                cluster.showOverly();
                            }
                        })
                    }
                });
            }
        })
        source.set('id', 'rqInfo');
        this.rqInfoSource = source;
        return source;
    },
    getRqInfoSourceForExtent: function (feature) {
        var source = new ol.source.Vector({
            format: new ol.format.GeoJSON({
                defaultDataProjection: 'EPSG:4326',
                featureProjection: 'EPSG:3857'
            }),
            loader: function (extent, resolution, projection) {
                var resultFeature = null;
                if (cluster.clickFeature != null) {
                    resultFeature = cluster.clickFeature;
                    cluster.clickFeature = null;
                } else {
                    resultFeature = cluster.getResultFeature();
                }
                if (resultFeature == null) {
                    return;
                }
                var id = resultFeature.get('id');
                cluster.rqInfoId = id;
                cluster.rqInfoCount = resultFeature.get('count');
                cluster.rqInfoName = resultFeature.get('name');
                var inputData = cluster.getInputData('cluster');
                inputData.communityId = id;
                $.ajax({
                    url: '/map/mapBuildingBankData3',
                    type: 'POST',
                    async: true,
                    data: inputData,
                    success: function (data) {
                        if (data.result.community == null) {
                            return;
                        }
                        var points = new Array();
                        var resultPoints = new Array()
                        var strPoint = $.trim(data.result.community.bound.slice(7).replace('((', '').replace('))', ''));
                        var point = strPoint.split(',');
                        point.forEach(function (point) {
                            var arrPoint = $.trim(point).split(' ');
                            var newArr = ol.proj.transform(arrPoint, 'EPSG:3857', 'EPSG:4326')
                            points.push(newArr);
                        })
                        resultPoints.push(points);
                        var jsonFeature = {
                            'type': 'Feature',
                            'geometry': {
                                'type': 'Polygon',
                                'coordinates': resultPoints
                            }
                        }
                        cluster.boundFeat = source.getFormat().readFeature(jsonFeature);

                        cluster.boundFeat.setStyle(new ol.style.Style({
                            stroke: new ol.style.Stroke({
                                color: 'rgba(250,176,117,1)',
                                width: 2
                            }),
                            fill: new ol.style.Fill({
                                color: 'rgba(255,179,91,0.2)'
                            })
                        }))
                        cluster.boundFeat.set('info', 'rqBound');
                        source.addFeature(cluster.boundFeat); //小区边界
                        inputData.communityName = data.result.community.communityName;
                        var hourseCount = data.result.community.totalHouseHoldCount;
                        map.getOverlays().clear();
                        var center = [data.result.community.arcgisX, data.result.community.arcgisY];
                        var divss = new Array();

                        var div = cluster.createRightDiv(inputData.communityName, hourseCount);
                        var id = Date.parse(new Date());
                        var centerOverly = new ol.Overlay({
                            id: id,
                            element: div,
                            position: [data.result.community.arcgisX, data.result.community.arcgisY],
                            offset: [-10, -30],
                            autoPan: true,
                            autoPanAnimation: {
                                duration: 250
                            }
                        })
                        map.addOverlay(centerOverly);

                        var divList = cluster.createDiv(data.result.mapDataList);
                        divList.forEach(function (item) {
                            var div = item[0];
                            //var point = ol.proj.transform(item[1], 'EPSG:4326', 'EPSG:3857');
                            var point = item[1];
                            var id = Date.parse(new Date());
                            var overly = new ol.Overlay({
                                id: id,
                                element: div,
                                position: point,
                                offset: [-10, -30],
                                autoPan: true,
                                autoPanAnimation: {
                                    duration: 250
                                }
                            })
                            map.addOverlay(overly);

                        })
                        cluster.showOverly();
                    }
                })
            }
        })
        source.set('id', 'rqInfo');
        this.rqInfoSource = source;
        return source;
    },
    getResultFeature: function () {
        var resultFeature = null;
        if (cluster.rqSource == null) {
            cluster.rqSource = new ol.source.Vector();
            $.ajax({
                url: '/map/mapCommunityData',
                type: 'POST',
                async: false,
                data: cluster.inputData,
                success: function (data) {
                    var list = data.result.mapDataList;
                    var zoom = map.getView().getZoom();
                    var radius = 1e6 / Math.pow(2, zoom - 2.3);
                    list.forEach(function (item) {
                        var center = [item.lng, item.lat];
                        var feature = new ol.Feature({
                            id: item.communityId,
                            geometry: new ol.geom.Circle(center, radius),
                            text: item.communityName.replace(/\s/g, "") + '\n' + item.count + '笔'
                        });
                        feature.set('name', item.communityName.replace(/\s/g, ""), false);
                        feature.set('count', item.count, false);
                        feature.set('type', 'rq', false);
                        cluster.rqSource.addFeature(feature);
                    })
                }
            })
        }
        var ext = map.getView().calculateExtent();
        var resultFeatures = cluster.rqSource.getFeaturesInExtent(ext);
        var minDistance = 0;
        resultFeatures.forEach(function (feature) {
            var point = feature.getGeometry().getCenter();
            var distance = new ol.Sphere(6378137).haversineDistance(point, cluster.mousePosition);
            if (minDistance == 0) {
                minDistance = distance;
                resultFeature = feature;
            } else {
                if (distance < minDistance) {
                    minDistance = distance;
                    resultFeature = feature;
                }
            }
        })
        return resultFeature;
    },
    setCircle: function (zoom) {
        if (this.vector.getSource() != null) {
            this.vector.getSource().forEachFeature(function (feature) {
                var geo = feature.getGeometry();
                if (geo.getType() == 'Circle') {
                    if (zoom < 14) {
                        geo.setRadius(1e6 / Math.pow(2, zoom - 2.5));
                    } else {
                        geo.setRadius(1e6 / Math.pow(2, zoom - 2.3));
                    }

                }
            })
        }
    },
    onResChange: function (e) {
        var id = cluster.vector.getSource().get('id');
        var zoom = map.getView().getZoom();
        if (zoom >= 5 && zoom < 10) {//省份
            map.getOverlays().clear();
            if (id != 'province') {
                cluster.vector.setSource(cluster.provinceSource);
            }
        } else if (zoom >= 10 && zoom < 14) { //市
            if (cluster.boundFeat != null) {
                cluster.removeFeature(cluster.rqInfoVector)
            }
            if (cluster.citySource != null) {
                if (id != 'city') {
                    cluster.vector.setSource(cluster.citySource);
                }
            }
        } else if (zoom >= 14 && zoom < 16) { // 县
            if (cluster.boundFeat != null) {
                cluster.removeFeature(cluster.rqInfoVector)
            }
            if (cluster.countySource != null) {
                if (id != 'county') {
                    cluster.vector.setSource(cluster.countySource);
                }
            }
        } else if (zoom >= 16 && zoom < 18) { // 小区
            if (cluster.selectFeature != null) {
                cluster.selectFeature.setStyle(cluster.selectStyle);
                cluster.selectFeature = null;
                cluster.selectStyle = null;
            }
            if (cluster.boundFeat != null) {
                cluster.removeFeature(cluster.rqInfoVector)
            }
            if (cluster.rqSource != null) {
                cluster.vector.setSource(cluster.rqSource);
            } else {
                var inputData = cluster.getInputData('clusterMap');
                cluster.vector.setSource(cluster.getRqSource(inputData))
            }
            map.getOverlays().clear();
        } else if (zoom >= 18) { // 小区详情
            if (cluster.isClick) {
                cluster.isClick = false;
                cluster.vector.setSource(new ol.source.Vector());
                return;
            }
            map.getOverlays().clear();
            if (cluster.rqInfoVector != null) {
                map.removeLayer(cluster.rqInfoVector);
            }
            cluster.vector.setSource(new ol.source.Vector());
            cluster.rqInfoVector = new ol.layer.Vector();
            cluster.rqInfoVector.setSource(cluster.getRqInfoSourceForExtent())
            map.addLayer(cluster.rqInfoVector);
        }
        cluster.setCircle(zoom);
    },
    onPointerMove: function (e) {
        var pixel = e.mapBrowserEvent.pixel;
        var features = [];
        map.forEachFeatureAtPixel(pixel, function (feature, layer) {
            if (layer != null) {
                if (layer.getVisible()) { // 当图层被隐藏之后,光标下该图层忽略
                    features.push(feature);
                }
            }
        });

        var len = features.length;
        var features_by_source;
        var zoom = map.getView().getZoom();
        if (zoom == 18) {
            return;
        }
        if (len == 1 && zoom >= 12) {
            if (features[0].get('info') != null) {
                return;
            }
            var type = features[0].getGeometry().getType();
            var style = features[0].getStyle();
            if (type == 'Circle') {
                var text = features[0].getProperties().text;
                features[0].setStyle(cluster.getSelectedPropertyStyle(type, text));
            } else if (type == 'Point') {
                features[0].setStyle(style);
            } else {
                var featureArr = map.getLayers().getArray();
                var featureArr_len = featureArr.length;
                for (var j = 0; j < featureArr_len; j++) {
                    if (typeof featureArr[j].setStyle !== 'undefined') {
                        var source = featureArr[j].getSource();
                        features_by_source = source.getFeatures();

                        var feature_len = features_by_source.length;
                        for (var m = 0; m < feature_len; m++) {
                            if (typeof features_by_source[m].getProperties().text === 'undefined') {
                                text = 'none';
                            } else {
                                var text = features_by_source[m].getProperties().text
                            }
                            var type = features_by_source[m].getGeometry().getType();
                            var style = features_by_source[m].getStyle();
                            features_by_source[m].setStyle(cluster.getUnselectedPropertyStyle(type, text, style, features_by_source[m]));
                        }
                    }
                }
            }
        } else if (len == 2) {
            var type1 = features[0].getGeometry().getType();
            var type2 = features[1].getGeometry().getType();

            if (type1 == 'Circle' || type2 == 'Circle') {
                if (features[0].N.id == features[1].N.id) {
                    for (var i = 0; i < len; i++) {
                        var text = features[i].getProperties().text;
                        var type = features[i].getGeometry().getType();
                        features[i].setStyle(cluster.getSelectedPropertyStyle(type, text));
                    }
                }
            }
        } else {
            var featureArr = map.getLayers().getArray();
            var featureArr_len = featureArr.length;
            for (var j = 0; j < featureArr_len; j++) {
                if (typeof featureArr[j].setStyle !== 'undefined') {
                    var source = featureArr[j].getSource();
                    features_by_source = source.getFeatures();

                    var feature_len = features_by_source.length;
                    for (var m = 0; m < feature_len; m++) {
                        if (typeof features_by_source[m].getProperties().text === 'undefined') {
                            text = 'none';
                        } else {
                            var text = features_by_source[m].getProperties().text
                        }
                        var type = features_by_source[m].getGeometry().getType();
                        var style = features_by_source[m].getStyle();
                        if (features_by_source[m].get('info') == null) {
                            features_by_source[m].setStyle(cluster.getUnselectedPropertyStyle(type, text, style, features_by_source[m]));
                        }
                    }
                }
            }
        }
    },
    onPointerClick: function (e) {
        var pixel = map.getEventPixel(e.originalEvent);
        var feature = map.forEachFeatureAtPixel(pixel, function (feature, layer) {
            return feature;
        });
        if (feature == null) {
            return;
        } else {
            cluster.selectStyle = feature.getStyle();
            cluster.selectFeature = feature;
            cluster.clickFeature = feature;
        }
        var center = feature.getGeometry().getCenter()
        var type = feature.get('type');
        var id = feature.N.id;
        switch (type) {
            case 'province': {
                map.getView().setCenter(center);
                map.getView().setZoom(8);
                var style = new ol.style.Style({
                    stroke: new ol.style.Stroke({
                        color: 'rgba(1, 1, 1,0)',
                        width: 0
                    })
                })
                feature.setStyle(style)
                cluster.vector.setSource(cluster.getCitySource(id));
            }
                break;
            case 'city': {
                $("#city").val(id + '00');
                $('#select2-chosen-1').text(feature.N.name);
                map.getView().setCenter(center);
                map.getView().setZoom(12);
                var inputData = cluster.getInputData('clusterMap');
                inputData.level = '3';
                var style = new ol.style.Style({
                    stroke: new ol.style.Stroke({
                        color: 'rgba(1, 1, 1,0)',
                        width: 0
                    })
                })
                feature.setStyle(style)
                cluster.vector.setSource(cluster.getCountySource(inputData));
            }
                break;
            case 'county': {
                map.getView().setCenter(center);
                map.getView().setZoom(16);
                var inputData = cluster.getInputData('clusterMap');
                var style = new ol.style.Style({
                    stroke: new ol.style.Stroke({
                        color: 'rgba(1, 1, 1,0)',
                        width: 0
                    })
                })
                feature.setStyle(style)
                inputData.district = id;
                cluster.vector.setSource(cluster.getRqSource(inputData));
            }
                break;
            case 'rq': {
                cluster.rqInfoName = feature.get('name');
                cluster.rqInfoCount = feature.get('count');
                cluster.rqInfoCenter = center;
                map.getView().setCenter(center);
                map.getView().setZoom(18);
                var style = new ol.style.Style({
                    stroke: new ol.style.Stroke({
                        color: 'rgba(1, 1, 1,0)',
                        width: 0
                    })
                })
                feature.setStyle(style);
            }
                break;
        }
    },
    getSelectedPropertyStyle: function (type, text) {
        var style = null;
        if (type == 'Circle') {
            style = new ol.style.Style({
                fill: new ol.style.Fill({
                    color: 'rgba(226, 74, 76, 1)',
                    opacity: '0.05'
                }),
                text: new ol.style.Text({
                    font: '10px',
                    textAlign: 'center',
                    rotateWithView: true,
                    text: text,
                    fill: new ol.style.Fill({
                        color: '#FFFFFF'
                    })
                })
            })
        }
        if (type == 'MultiPolygon' || type == 'Polygon') {
            style = new ol.style.Style({
                stroke: new ol.style.Stroke({
                    color: 'green',
                    width: 2
                }),
                fill: new ol.style.Fill({
                    color: 'rgba(76, 160, 101, 0.5)'
                })
            })
        }
        return style;
    },
    getUnselectedPropertyStyle: function (type, text, Style, feat) {
        var style = null;
        if (type == 'Point') { // 如果是点, 不去设置他的样式
            style = Style;
        }
        if (type == 'Circle') {
            var size = 5;
            var id = cluster.vector.getSource().get('id')
            var size = feat.get('count');
            var color = cluster.getColorForId(id, size);
            style = new ol.style.Style({
                fill: new ol.style.Fill({
                    color: color,
                    opacity: '0.05'
                }),
                text: new ol.style.Text({
                    font: '10px',
                    textAlign: 'center',
                    rotateWithView: true,
                    text: text,
                    fill: new ol.style.Fill({
                        color: 'rgba(255, 255, 255, 1)'
                    })
                })
            })
        }
        if (type == 'MultiPolygon' || type == 'Polygon') {
            style = new ol.style.Style({
                stroke: new ol.style.Stroke({
                    color: 'rgba(55, 155, 205, 1)',
                    width: 1
                })
            })
        }
        return style;
    },
    getText: function (list, name, zoneNumber) {
        var result = new Array()
        var text, count;
        if (list.length == 0) {
            count = 0;
            text = name + '\n' + '0笔';
            result[0] = text;
            result[1] = count;
            return result;
        } else {

            var result = [];
            var text = []
            for (var i = 0; i < list.length; i++) {
                var item = list[i];
                var zone = null;
                if (item.zoneNumber == null) {
                    zone = item.communityId
                } else {
                    zone = item.zoneNumber;
                }
                if (zoneNumber == zone) {
                    count = item.count;
                    text = xdmap.strWrap(name, 3) + '\n' + item.count + '笔';
                    result[0] = text;
                    result[1] = count;
                    break;
                } else {
                    count = 0;
                    text = xdmap.strWrap(name, 3) + '\n' + '0笔';
                    result[0] = text;
                    result[1] = count;
                }
            }
            return result;
        }
    },
    getCenter: function (id) {
        var cityId = id.substring(0, 2);
        var center = null;
        var url = '../../assets/newMap/data/mapdata/city/' + cityId + '.json';
        $.ajax({
            url: url,
            type: 'GET',
            async: false,
            success: function (data) {
                data.features.forEach(function (item) {
                    if (id == (item.properties.id + '00')) {
                        center = ol.proj.transform(item.properties.cp, 'EPSG:4326', 'EPSG:3857');
                        return;
                    }
                });
                if (center == null) {
                    center = ol.proj.transform(data.cp, 'EPSG:4326', 'EPSG:3857');
                }
            }
        })
        return center;
    },
    reset: function (inputData) {
        var zoom = null;
        var center = null;
        var inputData = this.getInputData('clusterMap');
        zoom = 11;
        if (inputData.city == '330100') {
            center = ol.proj.transform([120.1551500000, 30.2741500000], 'EPSG:4326', 'EPSG:3857');
        } else {
            center = cluster.getCenter(inputData.city);
        }
        inputData.level = '3';
        this.vector.setSource(this.getCountySource(inputData));
        map.getView().setZoom(zoom);
        map.getView().setCenter(center);
    },
    rqReset: function () {
        var inputData = cluster.getInputData('clusterMap');
        cluster.vector.setSource(cluster.getRqSource(inputData));
        map.getView().setZoom(16);
        map.getOverlays().clear();
    },
    setRqCenter: function (community, inputData) {
        var center = [community.lng, community.lat];
        this.inputData = inputData;
        cluster.rqInfoCount = community.count;
        cluster.rqInfoName = community.communityName;
        this.rqInfoSource = this.getRqInfoSource(inputData, center);
        cluster.vector.setSource(this.rqInfoSource);
        map.getView().setCenter(center);
        map.getView().setZoom(18);
        map.getOverlays().clear();
    },
    getInputData: function (currentMap) {
        var communityName = $("#search").val(),
            city = $('#city').val(),
            district = $('#district').val(),
            risk = $('#risk').val(),
            startDateStart = $('#startDateStart').val(),
            startDateEnd = $('#startDateEnd').val(),
            buildArea = $('#buildArea').val(),
            customCode = $('#customCode').val(),
            customValue = $('#customValue').val(),
            loansDuration = $('#loansDuration').val(),
            inputData = {
                communityName: communityName,
                city: city,
                district: district,
                risk: risk,
                startDateStart: startDateStart,
                startDateEnd: startDateEnd,
                buildArea: buildArea,
                loansDuration: loansDuration,
                currentMap: currentMap,
                customCode: customCode,
                customValue: customValue
            };
        return inputData;
    },//楼栋覆盖物
    createDiv: function (paramsData, inputData) {
        var resultList = new Array();
        var tmpList = new Array();
        var resultList, topDiv, sj, lastSmall, oneSmall;
        paramsData.forEach(function (searchEstate) {
            var div = document.createElement("div");
            searchEstate.forEach(function (data, i) {
                //自定义楼栋覆盖物
                var smallDiv;
                if (i != 0) {
                    if (oneSmall) oneSmall.style.padding = "6px 18px 6px 10px";
                    smallDiv = document.createElement('div');
                    smallDiv.appendChild(document.createTextNode(data.estateList.length + '笔'));
                    smallDiv.style.padding = "6px 18px 6px 10px";
                    smallDiv.style.borderRadius = '8px';
                    smallDiv.style.marginLeft = '-10px';
                    if (data.estateList[0].isantifraud == false) {
                        smallDiv.style.backgroundColor = "#62CB31";
                    } else if (data.estateList[0].isantifraud == true) {
                        smallDiv.style.backgroundColor = "#E51C23";
                    }
                    lastSmall = smallDiv;
                    topDiv.appendChild(smallDiv);
                } else {
                    if (lastSmall) lastSmall.style.padding = '6px 10px';

                    div.style.position = "absolute";
                    div.style.color = "white";
                    div.style.opacity = '0.95';
                    div.style.display = 'flex';
                    div.style.whiteSpace = "nowrap";
                    div.style.MozUserSelect = "none";
                    div.style.fontSize = "12px";
                    div.style.cursor = "pointer";
                    smallDiv = document.createElement('div');
                    smallDiv.appendChild(document.createTextNode(data.estateList.length + '笔'));
                    smallDiv.style.padding = "6px 10px";
                    smallDiv.style.borderRadius = "8px";
                    div.appendChild(smallDiv);
                    sj = this._p = document.createElement("p");
                    if (data.estateList[0].isantifraud == false) {
                        smallDiv.style.backgroundColor = "#62CB31";
                        sj.style.borderTop = "10px solid #62CB31";
                    } else if (data.estateList[0].isantifraud == true) {
                        smallDiv.style.backgroundColor = "#E51C23";
                        sj.style.borderTop = "10px solid #E51C23";
                    }
                    sj.style.position = "absolute";
                    sj.style.width = 0;
                    sj.style.height = 0;
                    sj.style.borderLeft = "10px solid transparent";
                    sj.style.borderRight = "10px solid transparent";
                    sj.style.bottom = "-20px";
                    sj.style.left = '6px';
                    div.appendChild(sj);
                    oneSmall = smallDiv;
                    lastSmall = null;
                    topDiv = div;
                }
                $(topDiv).hover(function () {
                    $(this).css('z-index', 11);
                }, function () {
                    $(this).css('z-index', 'auto')
                });
                topDiv.onclick = function () {
                    $(this).parent().siblings().children().children("div.row").css("display", "none");
                    $(this).parent().siblings().children().css('zIndex', 'auto');
                    $(this).css('zIndex', '11')
                    $(this).children('div.row').toggle();
                    if ($(this).children('div.row').length >= 1) return;
                    var listDiv = document.createElement("div");
                    listDiv.style.position = 'absolute';
                    listDiv.style.left = this.offsetWidth + 14 + "px";
                    listDiv.style.color = '#6a6c6f';
                    listDiv.style.width = '400px';
                    listDiv.style.whiteSpace = 'normal';
                    listDiv.className = 'row';
                    var col = document.createElement("div");
                    var hpanel = document.createElement("div");
                    hpanel.className = 'hpanel';
                    var hpanelHead = document.createElement("div");
                    hpanelHead.className = 'panel-heading hbuilt';
                    hpanelHead.onclick = function (e) {
                        e.stopPropagation()
                    };
                    var panelTools = document.createElement('div');
                    panelTools.className = 'panel-tools';
                    var closebox = document.createElement('a');
                    var closeIcon = document.createElement('i');
                    closeIcon.className = 'fa fa-times';
                    closebox.appendChild(closeIcon);
                    closebox.className = 'closebox';
                    var that = $(this);
                    closebox.onclick = function () {
                        that.children("div.row").css("display", "none");
                    };
                    panelTools.appendChild(closebox);
                    hpanelHead.appendChild(panelTools);
                    var aHref = document.createElement('a');
                    aHref.appendChild(document.createTextNode(data.estateList[0].communityname));
                    aHref.setAttribute('href', location.origin + '/mortgage/searchMortgage?communityId=' + cluster.rqInfoId);
                    hpanelHead.appendChild(aHref);
                    var hpanelBody = document.createElement("div");
                    hpanelBody.className = 'panel-body no-padding';
                    hpanelBody.style.maxHeight = '190px';
                    hpanelBody.style.overflowY = 'auto';
                    var listGroup = document.createElement('ul');
                    listGroup.className = 'list-group';
                    var hpanelFoot = document.createElement('div');
                    hpanelFoot.className = 'panel-footer';
                    hpanelBody.appendChild(listGroup);
                    hpanel.appendChild(hpanelHead);
                    hpanel.appendChild(hpanelBody);
                    hpanel.appendChild(hpanelFoot);
                    col.appendChild(hpanel);
                    listDiv.appendChild(col);
                    this.appendChild(listDiv);
                    searchEstate.forEach(function (data) {
                        var itemData = data.estateList;
                        itemData.forEach(function (data) {
                            var item = document.createElement('li');
                            item.className = 'list-group-item ';
                            var badge = document.createElement('span');
                            badge.className = 'badge badge-info';
                            if (data.isantifraud == false) {
                                badge.innerHTML = '未命中' ;
                            } else if (data.isantifraud == true) {
                                badge.innerHTML = '已命中' ;
                            }

                            item.appendChild(badge);
                            if (data.isantifraud == false) {
                                badge.style.backgroundColor = "#62CB31";
                            } else if (data.isantifraud == true) {
                                badge.style.backgroundColor = "#E51C23";
                            }
                            var borrName = document.createElement('span');
                            borrName.className = "borrName_";

                            borrName.appendChild(document.createTextNode(data.borrname));
                            item.appendChild(borrName);
                            item.appendChild(document.createTextNode(data.sourceaddress));
                            item.onclick = function () {
                                var href = window.location.origin + "/mortgage/show/" + data.mortgageid;
                                window.open(href);
                            };
                            listGroup.appendChild(item);
                        });
                    });
                    $(".borrName_").css("margin-right","6px");
                    var listLength = listGroup.children.length;
                    hpanelFoot.innerHTML = '共 ' + listLength + ' 笔';
                };
            });
            if (searchEstate.length > 0) {
                tmpList = new Array();
                tmpList[0] = topDiv;
                tmpList[1] = [searchEstate[0].lng, searchEstate[0].lat];
                resultList.push(tmpList);
            }

        });
        return resultList;
    },
    createRightDiv: function (inputData, hourseCount) {
        var div = this._div = document.createElement("div");
        var img = document.createElement('img');
        img.src = '/assets/accountLogo/zhoubian.png';
        div.style.position = "absolute";
        div.style.cursor = 'pointer';
        div.style.zIndex = '1';
        var message = document.createElement('div');
        message.style.position = 'absolute';
        message.style.border = '1px solid rgb(98, 203, 49)';
        message.style.background = '#fff';
        message.style.borderRadius = '6px';
        message.style.width = '230px';
        message.style.height = '50px';
        message.style.top = '-60px';
        message.style.left = '-98px';
        message.style.textAlign = 'center';
        var header = document.createElement('h5');
        header.innerHTML = cluster.rqInfoName;
        header.style.fontWeight = 'bold';
        header.style.color = '#62cb31';
        message.appendChild(header);
        var body = document.createElement('p');
        body.innerHTML = '贷款总量:<strong> ' + cluster.rqInfoCount + '</strong>&nbsp;&nbsp;&nbsp;总户数:<strong> ' + hourseCount + '</strong>';
        message.appendChild(body);
        var sj = this._p = document.createElement("p");
        sj.style.position = "absolute";
        sj.style.width = 0;
        sj.style.height = 0;
        sj.style.borderLeft = "10px solid transparent";
        sj.style.borderRight = "10px solid transparent";
        sj.style.bottom = "-20px";
        sj.style.left = '105px';

        sj.style.borderTop = "10px solid #62cb31";
        message.appendChild(sj);
        div.appendChild(message);
        div.appendChild(img);
        message.onclick = function () {
            var href = location.origin + '/mortgage/searchMortgage?communityId=' + cluster.rqInfoId + '&city=' + $('#city').val();
            window.open(href);
        };
        img.onclick = function () {
            $(this).siblings('div').toggle();
        };
        return div;
    },
    hiddenOverly: function () {
        var eleOverlys = $('.ol-overlay-container.ol-selectable');
        for (var i = 0; i < eleOverlys.length; i++) {
            var div = eleOverlys[i];
            var dis = div.style.display;
            if (dis != 'none') {
                div.style.display = 'none';
            }
        }
    },
    showOverly: function () {
        var eleOverlys = $('.ol-overlay-container.ol-selectable');
        for (var i = 0; i < eleOverlys.length; i++) {
            var div = eleOverlys[i];
            var dis = div.style.display;
            if (dis != 'block') {
                div.style.display = 'block';
            }
        }
    },
    getArea: function () {
        $("#district option").remove();
        $("#s2id_district span:first").html("行政区");
        var city = $("#city").val()
        $("#district").append("<option value='-1' >行政区</option>")
        if (city == '-1') {
            return
        }
        $.ajax({
            url: "/estate/districtList",
            type: "POST",
            async: false,
            data: {'city': city},
            success: function (result) {
                for (var i = 0; i < result.districtList.length; i++) {
                    $("#district").append("<option value=" + result.districtList[i].zoneNumber + ">" + result.districtList[i].name + "</option>")
                }
            }
        });
    },
    referrerInit: function (inputData) {
        var city = inputData["city"];
        var district = inputData['district'];
        var communityId = inputData['communityId'];
        this.init();
        if (city == '' || city == null) {
            return;
        } else {
            if (district == null || district == '' || district == -1) {
                $("#city").val(city);
                $("#city").change();
            } else {
                if (communityId == null || communityId == '') {
                    $("#city").val(city);
                    this.getArea();
                    $("#district").val(district);
                    $("#district").change();
                } else {
                    this.inputData = this.getInputData('clusterMap');
                    this.inputData.city = city;
                    this.inputData.district = district;
                    this.inputData.communityId = communityId;
                    $.ajax({
                        url: '/map/mapCommunityData',
                        type: 'POST',
                        async: true,
                        data: this.inputData,
                        success: function (data) {
                            //根据url的数据创建此小区的feature
                            //在根绝feature创建小区详情
                            if (data.result.mapDataList == null) {
                                return;
                            }
                            var item = data.result.mapDataList[0];
                            var zoom = map.getView().getZoom();
                            var radius = 1e6 / Math.pow(2, zoom - 2.3);
                            var center = [item.lng, item.lat];
                            var text = xdmap.strWrap(item.communityName.replace(/\s/g, ""), 3);
                            var feature = new ol.Feature({
                                id: item.communityId,
                                geometry: new ol.geom.Circle(center, radius),
                                text: text + '\n' + item.count + '笔'
                            });
                            feature.set('name', item.communityName.replace(/\s/g, ""), false);
                            feature.set('count', item.count, false);
                            feature.set('type', 'rq', false);
                            cluster.clickFeature = feature;
                            cluster.rqInfoName = item.communityName.replace(/\s/g, "");
                            cluster.rqInfoCount = item.count;
                            cluster.rqInfoCenter = center;
                            map.getView().setCenter(center);
                            map.getView().setZoom(18);
                        }
                    })
                }
            }
        }
    },
    getColorForId: function (id, size) {
        var color = 'rgba(76, 160, 101, 0.9)';
        switch (id) {
            case 'province': {
                color = 'rgba(76, 160, 101, 0.9)';
            }
                break;
            case 'city': {
                if (size > 700) {
                    color = "#26b095";
                } else if (size > 500) {
                    color = "#33c3a7"
                } else if (size > 300) {
                    color = "#4cdcc0";
                } else {
                    color = "#79ecd6";
                }
            }
                break;
            case 'county': {
                if (size > 700) {
                    color = "#26b095";
                } else if (size > 500) {
                    color = "#33c3a7"
                } else if (size > 300) {
                    color = "#4cdcc0";
                } else {
                    color = "#79ecd6";
                }
            }
                break;
            case 'rq': {
                if (size > 15) {
                    color = "#26b095";
                } else if (size > 10) {
                    color = "#33c3a7"
                } else if (size > 5) {
                    color = "#4cdcc0";
                } else {
                    color = "#79ecd6";
                }
            }
                break;
        }
        return color;
    },
    removeFeature: function (vector) {
        vector.getSource().forEachFeature(function (feature) {
            if (feature.get('info') == 'rqBound') {
                vector.getSource().removeFeature(feature)
            }
        })
    },
    addFeature: function (vector, feat) {
        var b = true;
        vector.getSource().forEachFeature(function (feature) {
            if (feature.get('info') == 'rqBound') {
                b = false;
            }
        })
        if (b) {
            vector.getSource().addFeature(feat);
        }
    }
}
